import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
// create an axios instance
const service = axios.create({
  // process.env.VUE_APP_BASE_API动态排至后台请求的基础地址
  baseURL: process.env.VUE_APP_BASE_API // url = base url + request url

})

// 请求拦截器=》发请求前执行
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // 场景；同意添加请求头，token
      config.headers.Authorization = `Bearer ${store.state.user.token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    // 状态码2xx，走这里
    const { data, message, success } = response.data
    if (success) {
      Message.success(message)
      return data
    } else {
      Message.error(message)
      return Promise.reject(new Error(message))
    }
  },
  error => {
    // 状态2xx以外，走这里
    console.log('err' + error) // for debug
    // 场景：如果token失效，返回登陆
    if (error.response.status === 401) {
      store.dispatch('user/deltuichu')
      router.replace(`/login?erorUrl=${router.currentRoute.path}`)
      Message({
        message: '登录超时',
        type: 'error'
      })
    }

    return Promise.reject(error)
  }
)

export default service
